package com.zealfi.wk.netty.udp;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;

/**
 * Created by kuan at 2018-06-14 下午 5:49
 */
public class LogEventBroadcaster {
    private final EventLoopGroup group;
    private final Bootstrap bootstrap;
    private final File file;

    public LogEventBroadcaster(InetSocketAddress address, File file) {
        this.group = new NioEventLoopGroup();
        this.bootstrap = new Bootstrap();
        this.bootstrap.group(group).channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new LogEventEncoder(address));
        this.file = file;
    }

    public void run() throws IOException {
        Channel channel = bootstrap.bind(0).syncUninterruptibly().channel();
        long pointer = 0;
        while (true) {
            long length = file.length();
            if (length < pointer) {
                pointer = length;
            } else {
                RandomAccessFile accessFile = new RandomAccessFile(file, "r");
                accessFile.seek(pointer);

                String line;
                while ((line = accessFile.readLine()) != null) {
                    System.out.println(new String(line.getBytes(CharsetUtil.ISO_8859_1), CharsetUtil.UTF_8));
                    channel.write(new LogEvent(null, file.getAbsolutePath(), line, -1));
                }
                channel.flush();
                pointer = accessFile.getFilePointer();
                accessFile.close();
            }

            try {
                Thread.sleep(1_000);
            } catch (InterruptedException e) {
                Thread.interrupted();
                break;
            }
        }
    }

    public void stop() {
        group.shutdownGracefully();
    }

    public static void main(String[] args) {
        int port = 4096;
        String path = "D:\\ali.txt";
        LogEventBroadcaster broadcaster = new LogEventBroadcaster(new InetSocketAddress("255.255.255.255", port), new File(path));

        try {
            try {
                broadcaster.run();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } finally {
            broadcaster.stop();
        }
    }
}
